<!--
 * @Author: ChunLai
 * @Date: 2022-01-07 08:51:46
 * @LastEditTime: 2025-11-20 15:47:57
 * @Description: 证件Ocr识别Pop弹出框
 * @FilePath: \01.latest-short-insure\src\views\form\components\OcrRecoganizeUpload.vue
-->
<template>
  <van-popup
    v-model="showDialog"
    lock-scroll
    overlay-class="lay1_shark"
    position="bottom"
    closeable
    round
    sticky
    get-container="body"
    @click-close-icon="closePop"
    @click-overlay="closePop"
  >
    <div class="pop-layout">
      <div class="pop-layout-head">
        {{ idType == "0" ? "OCR识别认证" : "证件照上传" }}
      </div>
      <WarnMsg :ocrType="ocrType" />
      <div class="pop-layout-conts">
        <div class="upload_msg_box mt10">
          <ImgUploadModule
            imgtype="face"
            :imgUrl="zUrl"
            :idType="idType"
            :ocrType="ocrType"
            @changeType="setImgType"
            @sendFile="afterRead"
          />
          <div>
            <OcrMsgs :msg="bankmsg" type="2" v-if="ocrType === 'bank'" />
            <OcrMsgs :msg="ocrMsg" type="1" v-else-if="idType == '0'" />
          </div>
        </div>
        <div class="upload_msg_box mt20" v-if="ocrType !== 'bank'">
          <ImgUploadModule
            imgtype="back"
            :imgUrl="fUrl"
            :idType="idType"
            :ocrType="ocrType"
            @changeType="setImgType"
            @sendFile="afterRead"
          />
          <div>
            <OcrMsgs :msg="ocrMsg" type="3" v-if="idType == '0'" />
          </div>
        </div>
      </div>
      <div class="pop-layout-btn">
        <div class="submit_btn" @click="sureOcrRes">提交</div>
      </div>
    </div>
  </van-popup>
</template>

<script>
import { mapGetters } from "vuex";
import { IdentityCodeValid } from "@/methods/userinfos.js";
import WarnMsg from "./ocr/WarnMsg";
import OcrMsgs from "./ocr/OcrMsgs";
import ImgUploadModule from "./ocr/ImgUploadModule";

export default {
  name: "OcrRecoganizeUpload",
  props: {
    showOcrPop: {
      type: Boolean,
      default: false,
    },
    onlyface: {
      type: Boolean,
      default: false,
    },
    ocrType: {
      type: String,
      default: "tbr", // bank
    },
    bankType: {
      type: String,
      default: "R", // bank
    },
  },
  components: { WarnMsg, OcrMsgs, ImgUploadModule },
  data() {
    return {
      zUrl: "",
      fUrl: "",
      imgtype: "",
      ocrMsg: {
        birthDate: "",
        idNum: "",
        name: "",
        sex: "",
        sexName: "",
        validDate: "",
        validDateEnd: "",
      },
      bankmsg: {
        bankAccNo: "",
        bankCodename: "",
        bankCode: "",
      },
      idType: "0",
      userObjInfo: {},
    };
  },
  computed: {
    ...mapGetters({
      bankList: "dictionary/bankList",
      longTime: "dictionary/longTime",
    }),
    showDialog: {
      get: function () {
        return this.showOcrPop;
      },
      set: function (value) {},
    },
  },
  created() {},
  methods: {
    initModule(userInfo) {
      if (userInfo.frontImg) {
        this.zUrl = userInfo.frontImg;
      }
      if (userInfo.backImg) {
        this.fUrl = userInfo.backImg;
      }
      if (userInfo.idNum) {
        this.idType = userInfo.idType;
        this.userObjInfo = userInfo;
      }
    },
    setImgType(value) {
      this.imgtype = value;
    },
    afterRead(file) {
      if (file.file.size > 204800) {
        let canvas = document.createElement("canvas");
        let context = canvas.getContext("2d");
        let img = new Image();
        img.src = file.content;
        img.onload = () => {
          const whRatio = img.width / img.height;
          const nw = 750;
          const nh = Math.ceil(nw / whRatio);
          canvas.width = nw;
          canvas.height = nh;
          context.drawImage(img, 0, 0, nw, nh);
          file.content = canvas.toDataURL(file.file.type, 0.92);
          this.getFileUpload(file.content);
        };
      } else {
        this.getFileUpload(file.content);
      }
    },
    // 公共接口
    getFileUpload(imgBase) {
      this.$store.commit("updateLoadTxt", "文件上传中，请稍后");
      let pic_base64 = imgBase
        .replace(new RegExp("image/jpeg", ""), "image/jpg")
        .replace(new RegExp("image/png", ""), "image/jpg");
      this.$store
        .dispatch("apis/comAliYunApi", {
          apiParams: {
            data: pic_base64,
          },
          apiName: "fileUpload",
        })
        .then((data) => {
          if (this.idType == "0") {
            this.checkIdNum(data.url, this.imgtype);
          } else {
            if (this.imgtype === "face") {
              this.zUrl = data.url;
            } else if (this.imgtype === "back") {
              this.fUrl = data.url;
            }
            this.saveImgInfo(data.url);
          }
        });
    },
    checkIdNum(imgUrl, imgtype) {
      this.$store.commit("updateLoadTxt", "OCR识别中，请稍后");
      this.$store
        .dispatch("apis/comAliYunApi", {
          apiParams: {
            url: imgUrl,
            side: imgtype, // face是脸，back是背面
          },
          apiName: "ocrIdCardRecoganize",
        })
        .then(({ data }) => {
          const resMsg = data.data,
            faceMsg = resMsg.frontResult,
            backMsg = resMsg.backResult;
          this.$nextTick(() => {
            if (imgtype === "face") {
              if (faceMsg.name) {
                this.ocrMsg.name = faceMsg.name;
              }
              if (faceMsg.iDNumber) {
                let idFlag = IdentityCodeValid(faceMsg.iDNumber);
                if (idFlag) {
                  this.ocrMsg.idNum = faceMsg.iDNumber;
                  // 出生日期和性别 用身份证计算的结果 减少失败误差
                  this.setBirthSex(faceMsg.iDNumber);
                  this.saveImgInfo(imgUrl, faceMsg.iDNumber);
                } else {
                  this.$toast("身份证识别有误，您可以提交后手动输入");
                }
              }
              this.zUrl = imgUrl;
            } else if (imgtype === "back") {
              if (backMsg.startDate) {
                this.ocrMsg.validDate = this.formatDate(backMsg.startDate);
              }
              if (backMsg.endDate) {
                this.ocrMsg.validDateEnd =
                  backMsg.endDate === "长期"
                    ? this.longTime
                    : this.formatDate(backMsg.endDate);
              }
              if (!backMsg.endDate || !backMsg.startDate) {
                this.$toast("身份证有效期识别有误，您可以提交后手动修改");
              }
              this.saveImgInfo(imgUrl);
              this.fUrl = imgUrl;
            }
          });
        });
    },
    formatDate(val) {
      return `${val.substring(0, 4)}-${val.substring(4, 6)}-${val.substring(
        6,
        8
      )}`;
    },
    setBirthSex(iDNumber) {
      const year = `${iDNumber.substring(6, 10)}`,
        month = `${iDNumber.substring(10, 12)}`,
        day = `${iDNumber.substring(12, 14)}`,
        xbnum = iDNumber.substring(16, 17);
      this.ocrMsg.birthDate = `${year}-${month}-${day}`;
      this.ocrMsg.sex = xbnum % 2 === 0 ? "1" : "0";
      this.ocrMsg.sexName = xbnum % 2 === 0 ? "女" : "男";
    },
    sureOcrRes() {
      if (!this.zUrl) {
        return this.$toast("请拍摄证件照正面");
      }
      // this.idType == "0" &&
      if (!this.fUrl) {
        return this.$toast("请拍摄证件照反面");
      }
      this.ocrMsg.zPicUrl = this.zUrl || "";
      this.ocrMsg.fPicUrl = this.fUrl || "";
      this.$emit("sureBtn", this.ocrMsg);
    },
    closePop() {
      this.$emit("sureBtn", null);
    },
    saveImgInfo(picUrl, idNumber = "") {
      let userType = "",
        imgType = "";
      // 证件用户类型
      if (this.ocrType === "bbr") {
        userType = "21"; //被保人
      } else if (this.ocrType === "tbr") {
        userType = "20"; //投保人
      }
      if (this.imgtype === "face") {
        imgType = "5";
      } else if (this.imgtype === "back") {
        imgType = "6";
      }
      let params = {
        ...this.apiComParams,
        type: userType,
        imgType: imgType,
        imgUrl: picUrl,
        idNum: idNumber || this.userObjInfo.idNum || "",
        ocrFlag: "Y",
      };
      this.$store.dispatch("apis/comAdminApiRequest", {
        apiParams: params,
        apiName: "saveImg",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.pop-layout {
  &-head {
    width: 100%;
    height: 50px;
    line-height: 50px;
    font-size: 16px;
    font-weight: 600;
    font-family: MiSans;
    text-align: center;
    position: relative;
    border-bottom: 1px solid #f5f5f5;
  }
  &-conts {
    width: 100%;
    min-height: 280px;
    padding: 10px 12px;
  }
  &-btn {
    display: flex;
    align-items: center;
    width: 100%;
    height: 50px;
    padding: 0 12px;
    box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.3);
    .submit_btn {
      width: 100%;
      height: 40px;
      line-height: 40px;
      border-radius: 22px;
      font-size: 15px;
      text-align: center;
      border: 1px solid #f54040;
      color: #fff;
      background: #f54040;
    }
  }
}
.upload_msg_box {
  display: flex;
  width: 100%;
  height: 130px;
  margin-bottom: 20px;
}

.ocr-recoganize-pop {
  /deep/.van-overlay {
    z-index: 99 !important;
  }

  /deep/.van-popup--bottom {
    z-index: 100 !important;
  }

  /deep/.van-popup__close-icon {
    z-index: 5 !important;
  }
}
</style>
